package com.ilop.sthome.ui.activity.detail.common;

import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.ilop.sthome.ui.activity.main.ContainLoginActivity;
import com.example.common.utils.LiveDataBus;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.common.command.SiterCommand;
import com.ilop.sthome.data.event.EventAnswerOK;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.mvp.contract.scene.DefaultContract;
import com.ilop.sthome.mvp.present.scene.DefaultPresenter;
import com.ilop.sthome.ui.adapter.scene.TriggerInAdapter;
import com.ilop.sthome.ui.adapter.scene.TriggerOutAdapter;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityCommonFunctionBinding;

import java.util.List;

/**
 * @author skygge
 * @date 2020-03-14.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：常用功能详情显示
 */
public class CommonFunctionActivity extends ContainLoginActivity<DefaultPresenter, ActivityCommonFunctionBinding> implements DefaultContract.IView {

    private long mDefaultId;

    private TriggerInAdapter mInAdapter;
    private TriggerOutAdapter mOutAdapter;

    private List<DeviceInfoBean> inputList;
    private List<DeviceInfoBean> outputList;

    private boolean hasModify;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_common_function;
    }

    @Override
    protected void initialize() {
        super.initialize();
        mDefaultId = getIntent().getLongExtra(CommonId.KEY_RECOMMEND_ID, -1);
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresent = new DefaultPresenter(mContext);
    }

    @Override
    protected void initView() {
        super.initView();
        mPresent.getDefaultData(mDefaultId);
    }

    @Override
    protected void initData() {
        super.initData();
        mPresent.getInputDevice();
        mPresent.getOutputDevice();
        mPresent.getMappingScene();
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.ivBack.setOnClickListener(view -> mPresent.whetherToSave(hasModify));
        mDBind.defaultAddIn.setOnClickListener(v -> mPresent.addNewInput());
        mDBind.defaultAddOut.setOnClickListener(v -> mPresent.addNewOutput());
        mDBind.rlMapping.setOnClickListener(v -> mPresent.chooseMapping());
        mDBind.tvSaveDefault.setOnClickListener(v -> mPresent.saveAction());
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with(CommonId.INPUT_CLICK, Integer.class).observe(this, integer ->
                mPresent.updateAction(true, integer));

        LiveDataBus.get().with(CommonId.OUTPUT_CLICK, Integer.class).observe(this, integer ->
                mPresent.updateAction(false, integer));

        LiveDataBus.get().with(CommonId.INPUT_CONDITION, DeviceInfoBean.class).observe(this, device -> {
            assert device != null;
            if (mPresent.checkInput(device)){
                inputList.add(device);
                mPresent.setInputList(inputList);
                hasModify = true;
            }
        });

        LiveDataBus.get().with(CommonId.OUTPUT_CONDITION, DeviceInfoBean.class).observe(this, device -> {
            assert device != null;
            if (mPresent.checkOutput(device)){
                if ("PHONE".equals(device.getDevice_type())){
                    outputList.add(0, device);
                }else {
                    outputList.add(device);
                }
                mPresent.setOutputList(outputList);
                hasModify = true;
            }
        });

        LiveDataBus.get().with(CommonId.INPUT_UPDATE, DeviceInfoBean.class).observe(this, device -> {
            mPresent.checkUpdateInput(device);
            hasModify = true;
        });
        LiveDataBus.get().with(CommonId.OUTPUT_UPDATE, DeviceInfoBean.class).observe(this, device -> {
            mPresent.checkUpdateOutput(device);
            hasModify = true;
        });
        LiveDataBus.get().with(CommonId.DELETE_CONDITION, Boolean.class).observe(this, isInput -> {
            mPresent.deleteAction(isInput);
            hasModify = true;
        });
        LiveDataBus.get().with(CommonId.KEY_SUCCESS, List.class).observe(this, list -> {
            mPresent.getMappingScene(list, true);
            hasModify = true;
        });

        LiveDataBus.get().with(CommonId.KEY_ANSWER_OK, EventAnswerOK.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "initDataBus: answerOK");
                dismissProgressDialog();
                if (event.getData_str1().length() == 9) {
                    String code = event.getData_str2();
                    int cmd = Integer.parseInt(event.getData_str1().substring(0, 4), 16);
                    if (cmd == SiterCommand.INCREASE_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            mPresent.onSaveSuccess(code.substring(3));
                        } else {
                            showToast(getString(R.string.failed));
                        }
                    }else if (cmd == SiterCommand.MODIFY_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            showMsg(getString(R.string.modify_successfully));
                            mPresent.onSaveSuccess(code.substring(3));
                        } else {
                            showToast(getString(R.string.failed));
                        }
                    }
                }
            }
        });
    }

    @Override
    public void showTitle(String msg) {
        mDBind.tvDefaultTitle.setText(msg);
    }

    @Override
    public void showEditable(boolean editable) {
        mDBind.defaultAddIn.setVisibility(editable ? View.VISIBLE : View.GONE);
        mDBind.defaultAddOut.setVisibility(editable ? View.VISIBLE : View.GONE);
        mDBind.ivDefaultRight.setVisibility(editable ? View.VISIBLE : View.INVISIBLE);
        mDBind.tvSaveDefault.setVisibility(editable ? View.VISIBLE : View.GONE);
        mInAdapter = new TriggerInAdapter(mContext);
        mInAdapter.setEditable(editable);
        mInAdapter.setFirstDefault(true);
        mDBind.triggerList.setAdapter(mInAdapter);
        mDBind.triggerList.setLayoutManager(new LinearLayoutManager(mContext));
        mOutAdapter = new TriggerOutAdapter(mContext);
        mOutAdapter.setEditable(editable);
        mDBind.executiveList.setAdapter(mOutAdapter);
        mDBind.executiveList.setLayoutManager(new LinearLayoutManager(mContext));
        mDBind.rlMapping.setEnabled(editable);
    }

    @Override
    public void showInputList(List<DeviceInfoBean> input) {
        inputList = input;
        mInAdapter.setList(input);
    }

    @Override
    public void showOutputList(List<DeviceInfoBean> output) {
        outputList = output;
        mOutAdapter.setList(output);
    }

    @Override
    public void showMapping(String scene) {
        mDBind.defaultSceneIn.setText(scene);
    }

    @Override
    public void showMsg(String msg) {
        runOnUiThread(()->showToast(msg));
    }

    @Override
    public void showProgress() {
        showProgressDialog();
    }

    @Override
    public void startActivityByIntent(Intent intent) {
        startActivity(intent);
    }

    @Override
    public void finishActivity() {
        dismissProgressDialog();
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mPresent.whetherToSave(hasModify);
            return true;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }
}
